import axios, {
  AxiosError,
  type AxiosInstance,
  type AxiosResponse,
  type InternalAxiosRequestConfig,
} from 'axios';
import { useUserStore } from '@/stores/user';
import { createDiscreteApi, useDialog } from 'naive-ui';
import router from '@/router';

const { message, dialog } = createDiscreteApi(['message', 'dialog']); // ✅ 可在任何地方使用

const request: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_BASE_API,
});

request.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  const userStore = useUserStore();
  const token = userStore.getToken();

  if (token) {
    config.headers['Authorization'] = `Bearer ${token}`;
  }
  return config;
});

request.interceptors.response.use(
  (res: AxiosResponse) => {
    const userStore = useUserStore();

    if (res.data.code === 200) {
      return res.data;
    }

    if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
      return res.data;
    }

    if (res.data.code === 401) {
      message.error('登录状态已过期，请重新登录');
      // dialog.info({
      //   title: '提示',
      //   content: '登录状态已过期，请重新登录',
      //   positiveText: '重新登录',
      //   onPositiveClick: () => {
      //     userStore.logout();
      //     router.push('/login');
      //   },
      // });
      return Promise.reject(res.data);
    }

    // 其他错误
    message.error(res.data.msg);
    return res.data;
  },
  (error: AxiosError) => {
    message.error(error.message);
    return Promise.reject(error);
  },
);

export default request;
